package org.example.sqlsession;

import org.example.config.Function;
import org.example.config.MapperBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

public class MyMapperProxy implements InvocationHandler {
    private MySqlsession sqlSession;
    private MyConfiguration configuration;

    public MyMapperProxy(MySqlsession sqlSession, MyConfiguration configuration) {
        this.sqlSession = sqlSession;
        this.configuration = configuration;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MapperBean mapperBean = configuration.readMapper("UserMapper.xml");
        if (!Objects.equals(method.getDeclaringClass().getName(), mapperBean.getInterfaceName())) {
            return null;
        }
        List<Function> functionList = mapperBean.getList();
        if (functionList != null) {
            for (Function function : functionList) {
                if (Objects.equals(method.getName(), function.getFuncName())) {
                    return sqlSession.selectOne(function.getSql(), String.valueOf(args[0]));
                }
            }
        }
        return null;
    }
}
